package com.hc.dao.impl;

import com.hc.dao.UserDao;
import com.hc.entiry.UserEntity;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

/**
 * @Description TODO
 * @Date 2018/12/18 16:54
 * @Created by hecong
 */
@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 创建对象
     * @param user
     */
    @Override
    public void saveUser(UserEntity user) {
        mongoTemplate.save(user);
    }

    /**
     * 根据用户名查询对象
     * @param username
     * @return
     */
    @Override
    public UserEntity findUserByUsername(String username) {
        Query query = new Query(Criteria.where("username").is(username));
        UserEntity user = mongoTemplate.findOne(query, UserEntity.class);
        return user;
    }

    /**
     * 更新对象
     * @param user
     * @return
     */
    @Override
    public long updateUser(UserEntity user) {
        Query query = new Query(Criteria.where("id").is(user.getId()));
        Update update = new Update().set("username", user.getUsername()).set("password", user.getPassword());
        //更新查询返回结果集的第一条
        UpdateResult result = mongoTemplate.updateFirst(query, update, UserEntity.class);
        if(result != null) {
            return result.getModifiedCount();
        }else {
            return 0L;
        }
    }

    /**
     * 删除对象
     * @param id
     */
    @Override
    public void deleteUser(Long id) {
        Query query = new Query(Criteria.where("id").is(id));
        mongoTemplate.remove(query, UserEntity.class);
    }
}
